package top.fangw.common.flyway.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;

/**
 * @description: 创建数据库
 * @author: fgw
 * @createDate: 2024/1/11
 */
@Slf4j
@Component
public class CreateDatabase {
    public static void init(String URL, String username, String password, String dbName) {
        String sql = String.format("""
                CREATE DATABASE if not exists `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
                """, dbName);
        Connection connection;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (Exception e) {
            throw new RuntimeException("数据源驱动加载失败，请检查相关配置");
        }
        try {
            connection = DriverManager.getConnection(URL, username, password);
        } catch (Exception e) {
            throw new RuntimeException("数据源连接失败，请检查相关配置");
        }
        try {
            Statement statement;
            try {
                statement = connection.createStatement();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                statement.executeUpdate(sql);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } finally {
            if (Objects.nonNull(connection)) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        log.info("数据库：{}创建成功", dbName);
    }
}
